﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Management;
using System.DirectoryServices;
using System.Threading;

namespace SystemsAdmin
{
    class WindowsDomainRepository : ComputerRepository
    {
        
        public string DomainName {get; set;}
        public string CompGroupName {get; set;}

        /// <summary>
        /// Gets the compouters from a group in a Windows Domain and gets each of the computers's
        /// IP address and MAC address using WMI
        /// </summary>
        /// <returns></returns>
        public List<Computer> GetAllComputers()
        {
            ManagementObjectSearcher query1;
            ManagementObjectCollection queryCollection1;
            ManagementScope RemoteConn;
            string ip_address = "", mac_address = "";
            ObjectQuery oQuery = new ObjectQuery("Select MacAddress,IPAddress from Win32_NetworkAdapter  where IPEnabled=TRUE");

            //ConnectionOptions options = new ConnectionOptions();
            //options.Username = domain + "\\" + sUserName; //could be in domain\user format
            //options.Password = sPwd;

            List<Computer> computers_in_domain = new List<Computer>();
            DirectoryEntry de = new DirectoryEntry("WinNT://" + DomainName);
            //de.Children.SchemaFilter.Add("StaffComputers");
            de.Children.SchemaFilter.Add("computer");
            foreach (DirectoryEntry machine in de.Children)
            {
                try
                {
                    RemoteConn = new ManagementScope("\\\\" + machine.Name + "\\root\\cimv2");
                    query1 = new ManagementObjectSearcher(RemoteConn, oQuery);
                    queryCollection1 = query1.Get();

                    foreach (ManagementObject mo in queryCollection1)
                    {
                        int nrIP = ((System.Array)(mo["IPAddress"])).Length;
                        for (int c = 0; c < nrIP; c++)
                        {
                            ip_address = ((System.Array)(mo["IPAddress"])).GetValue(c).ToString();
                            mac_address = mo["MacAddress"].ToString();
                            if (ip_address.Contains("."))
                                break;
                        }
                        if (ip_address.Contains(".") && ip_address  != "0.0.0.0")
                            break;
                    }
                }
                catch (Exception e)
                {
                    Console.Error.WriteLine("Failed to connect to: " + machine.Name + "\n Error Message: " + e.Message);
                } 
                Computer new_comp = new Computer(mac_address,
                        machine.Name,
                        ip_address);
                computers_in_domain.Add(new_comp);
                new Thread(new_comp.Refresh).Start();
            }
            return computers_in_domain;
        }

    }
}
